#include "sys.h"

char* HexToString(uint16_t hex)
{
    char* str = malloc(10);  // 分配足够的内存空间来存储转换后的字符串
    sprintf(str, "%04x", hex);  // 使用 sprintf 函数将十六进制数转换为字符串
    return str;
}

char* IntToString(int num)
{
    char* str = malloc(10);
    if(str != NULL)
    {
        sprintf(str, "%d", num);
        return str;
    }
    else return NULL;
}
char* FloatToString(float num)
{
	char* str = malloc(10);
    if(str != NULL)
    {
        sprintf(str, "%.1f", num);
        return str;
    }
    else return NULL;
}

void BitToString(uint8_t data, char* array)
{
    for(uint8_t i=0; i<8; i++)
    {
        if(data & 0x80)   array[i] = '1';
        else    array[i] = '0';
        data <<= 1;
    }
}

//计算数据校验和
uint8_t ADD8_Calculation(uint8_t *array, uint8_t length)
{
    uint8_t add = 0;
    for(uint8_t i=0; i<length; i++)
    {
        add += array[i];
    }
    return add;
}
//校验数据和
uint8_t ADD8_Check(uint8_t *array, uint8_t length)
{
    uint8_t add = 0;
    for(uint8_t i=0; i<length-1; i++)
    {
        add += array[i];
    }
    if(add == array[length-1])  return  1;
    else    return  0;
}

void Flash_Init(void)
{
    if(*(__IO uint16_t*)WRITE_START_ADDR != 0xffff)
    {
        printf("Flash starting erase.\n");
        FLASH_Unlock();     //解锁flash
        if(FLASH_ErasePage(WRITE_START_ADDR) != FLASH_COMPLETE)  //开始擦写
        {
            printf("Flash init failed!\n");
            FLASH_Lock();       //锁定flash
            return;
        }
    }
    printf("Flash init complete.\n");
}

//flash读写 半字节
void Flash_Write(uint32_t address, uint16_t* data, uint16_t length)
{
    FLASH_Unlock();     //解锁flash
    
    for (uint16_t i = 0; i < length; i++) {
        // 等待上一次操作完成或超时
        if(FLASH_WaitForLastBank1Operation(0x2000) != FLASH_COMPLETE)    return;

        // 设置PG位以编程Flash
        FLASH->CR |= FLASH_CR_PG;

        // 写入数据到Flash
        *(__IO uint16_t*)address = data[i];
        
        // 等待编程完成
        if(FLASH_WaitForLastBank1Operation(0x2000) != FLASH_COMPLETE)    return;

        // 清除PG位
        FLASH->CR &= ~FLASH_CR_PG;
        
        // 增加地址
        address += 2;
    }
    
    FLASH_Lock();   //锁定flash
}

void Flash_Read(uint32_t address, uint16_t* data, uint16_t length)
{
    for (uint16_t i = 0; i < length; i++) {
        data[i] = *(__IO uint16_t*)address;
        address += 2;
    }
}
